﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using FisApp.enums;
using FisApp.utility;
using System.Data.SqlClient;
using DevExpress.XtraGrid.Views.Grid;

namespace FisApp
{
    public partial class FrmModel: Form
    {
        #region Variables...
        private string modelId;
        private string sqlCommandType = SqlCommandType.INSERT;
        private OpenFileDialog fDialog;
        string imageName;
        string imagePath;

        public int? kalite
        {
            get
            {
                return (int?)kaliteLookUp.EditValue;
            }
            set
            {
                kaliteLookUp.EditValue = value;
            }
        }

        public int? taban
        {
            get
            {
                return (int?)tabanLookUp.EditValue;
            }
            set
            {
                tabanLookUp.EditValue = value;
            }
        }

        public int? renk
        {
            get
            {
                return (int?)renkLookUp.EditValue;
            }
            set
            {
                renkLookUp.EditValue = value;
            }
        }

        public int? deri
        {
            get
            {
                return (int?)deriLookUp.EditValue;
            }
            set
            {
                deriLookUp.EditValue = value;
            }
        }

        public int? astar
        {
            get
            {
                return (int?)astarLookUp.EditValue;
            }
            set
            {
                astarLookUp.EditValue = value;
            }
        }

        public int? lazer
        {
            get
            {
                return (int?)lazerLookUp.EditValue;
            }
            set
            {
                lazerLookUp.EditValue = value;
            }
        }

        public int? elSarac
        {
            get
            {
                return (int?)elSaracLookUp.EditValue;
            }
            set
            {
                elSaracLookUp.EditValue = value;
            }
        }

        public int? makineSarac
        {
            get
            {
                return (int?)makineSaracLookUp.EditValue;
            }
            set
            {
                makineSaracLookUp.EditValue = value;
            }
        }

        public Bitmap resim
        {
            get
            {
                return (Bitmap)peResim.EditValue;
            }
            set
            {
                peResim.EditValue = value;
            }
        }

        public DataTable Modeller
        {
            get
            {
                return (DataTable)gcModel.DataSource;
            }

            set
            {
                gcModel.DataSource = value;
            }
        }

        public DataRow SelectedRow
        {
            get
            {
                return gvModel.GetDataRow(gvModel.FocusedRowHandle);
            }
        }
        #endregion

        #region Constructor...
        public FrmModel()
        {
            InitializeComponent();
        }
        #endregion

        #region Methods....
        private void clearForm()
        {
            modelId = null;
            kalite = null;
            taban = null;
            renk = null;
            deri = null;
            astar = null;
            lazer = null;
            elSarac = null;
            makineSarac = null;
            resim = null;
            btnVazgec.Visible = false;
            sqlCommandType = SqlCommandType.INSERT;
        }

        private void LoadModeller()
        {
            try
            {
                string query = @"SELECT * FROM model m 
                                   JOIN kalite k ON k.kalite_id = m.kalite_id
                                   JOIN taban t ON t.taban_id = m.taban_id
                                   JOIN renk r ON r.renk_id = m.renk_id
                                   JOIN deri d ON d.deri_id = m.deri_id
                              LEFT JOIN astar a ON a.astar_id = m.astar_id
                              LEFT JOIN lazer l ON l.lazer_id = m.lazer_id
                              LEFT JOIN elsarac e ON e.elsarac_id = m.elsarac_id
                              LEFT JOIN makinesarac ms ON ms.makinesarac_id = m.makinesarac_id";
                DataSet ds = DBUtils.SQLSelect(query, null);
                if (ds == null)
                    return;

                if (ds.Tables.Count != 0)
                    Modeller = ds.Tables[0];

                gvModel.BestFitColumns();
            }
            catch (Exception ex)
            {
                FrmMessage.showDialog("Hata :" + ex.Message, MessageTypes.Error);
            }
        }

        private void LoadKalite()
        {
            try
            {
                string query = "SELECT k.*, kalite_no + ' - ' + kalip_no as kalite_kalip FROM kalite k";
                DataSet ds = DBUtils.SQLSelect(query, null);
                if (ds == null)
                    return;

                if (ds.Tables.Count != 0)
                {
                    kaliteLookUp.Properties.DataSource = ds.Tables[0];
                    kaliteLookUp.Properties.DisplayMember = "kalite_kalip";
                    kaliteLookUp.Properties.ValueMember = "kalite_id";
                }
            }
            catch (Exception ex)
            {
                FrmMessage.showDialog("Hata :" + ex.Message, MessageTypes.Error);
            }
        }

        private void LoadTaban()
        {
            try
            {
                string query = "SELECT t.*, taban_marka + ' - ' + taban_no +' - '+ taban_renk as taban_marka_no_renk  FROM taban t WHERE kalite_id=@kalite_id";

                List<SqlParameter> list = new List<SqlParameter>();
                list.Add(DBUtils.GetParameter("@kalite_id", kalite));
                DataSet ds = DBUtils.SQLSelect(query, list);
                if (ds == null)
                    return;

                if (ds.Tables.Count != 0)
                {
                    tabanLookUp.Properties.DataSource = ds.Tables[0];
                    tabanLookUp.Properties.DisplayMember = "taban_marka_no_renk";
                    tabanLookUp.Properties.ValueMember = "taban_id";
                }
            }
            catch (Exception ex)
            {
                FrmMessage.showDialog("Hata :" + ex.Message, MessageTypes.Error);
            }
        }

        private void LoadRenk()
        {
            try
            {
                string query = "SELECT r.*, renk_kodu + ' - ' + renk_aciklama as renk_kod_aciklama  FROM renk r";
                DataSet ds = DBUtils.SQLSelect(query, null);
                if (ds == null)
                    return;

                if (ds.Tables.Count != 0)
                {
                    renkLookUp.Properties.DataSource = ds.Tables[0];
                    renkLookUp.Properties.DisplayMember = "renk_kod_aciklama";
                    renkLookUp.Properties.ValueMember = "renk_id";
                }
            }
            catch (Exception ex)
            {
                FrmMessage.showDialog("Hata :" + ex.Message, MessageTypes.Error);
            }
        }

        private void LoadDeri()
        {
            try
            {
                string query = "SELECT d.*, deri_kodu + ' - ' + deri_aciklama as deri_kod_aciklama FROM deri d";
                DataSet ds = DBUtils.SQLSelect(query, null);
                if (ds == null)
                    return;

                if (ds.Tables.Count != 0)
                {
                    deriLookUp.Properties.DataSource = ds.Tables[0];
                    deriLookUp.Properties.DisplayMember = "deri_kod_aciklama";
                    deriLookUp.Properties.ValueMember = "deri_id";
                }
            }
            catch (Exception ex)
            {
                FrmMessage.showDialog("Hata :" + ex.Message, MessageTypes.Error);
            }
        }

        private void LoadAstar()
        {
            try
            {
                string query = "SELECT a.*, astar_kodu + ' - ' + astar_aciklama as astar_kod_aciklama FROM astar a";
                DataSet ds = DBUtils.SQLSelect(query, null);
                if (ds == null)
                    return;

                if (ds.Tables.Count != 0)
                {
                    astarLookUp.Properties.DataSource = ds.Tables[0];
                    astarLookUp.Properties.DisplayMember = "astar_kod_aciklama";
                    astarLookUp.Properties.ValueMember = "astar_id";
                }
            }
            catch (Exception ex)
            {
                FrmMessage.showDialog("Hata :" + ex.Message, MessageTypes.Error);
            }
        }

        private void LoadLazer()
        {
            try
            {
                string query = "SELECT l.*, lazer_kodu + ' - ' + lazer_aciklama as lazer_kod_aciklama FROM lazer l";
                DataSet ds = DBUtils.SQLSelect(query, null);
                if (ds == null)
                    return;

                if (ds.Tables.Count != 0)
                {
                    lazerLookUp.Properties.DataSource = ds.Tables[0];
                    lazerLookUp.Properties.DisplayMember = "lazer_kod_aciklama";
                    lazerLookUp.Properties.ValueMember = "lazer_id";
                }
            }
            catch (Exception ex)
            {
                FrmMessage.showDialog("Hata :" + ex.Message, MessageTypes.Error);
            }
        }

        private void LoadElSarac()
        {
            try
            {
                string query = "SELECT e.*, elsarac_kodu + ' - ' + elsarac_aciklama as elsarac_kod_aciklama  FROM elsarac e";
                DataSet ds = DBUtils.SQLSelect(query, null);
                if (ds == null)
                    return;

                if (ds.Tables.Count != 0)
                {
                    elSaracLookUp.Properties.DataSource = ds.Tables[0];
                    elSaracLookUp.Properties.DisplayMember = "elsarac_kod_aciklama";
                    elSaracLookUp.Properties.ValueMember = "elsarac_id";
                }
            }
            catch (Exception ex)
            {
                FrmMessage.showDialog("Hata :" + ex.Message, MessageTypes.Error);
            }
        }

        private void LoadMakineSarac()
        {
            try
            {
                string query = "SELECT m.*, makinesarac_kodu + ' - ' + makinesarac_aciklama as makinesarac_kod_aciklama FROM makinesarac m";
                DataSet ds = DBUtils.SQLSelect(query, null);
                if (ds == null)
                    return;

                if (ds.Tables.Count != 0)
                {
                    makineSaracLookUp.Properties.DataSource = ds.Tables[0];
                    makineSaracLookUp.Properties.DisplayMember = "makinesarac_kod_aciklama";
                    makineSaracLookUp.Properties.ValueMember = "makinesarac_id";
                }
            }
            catch (Exception ex)
            {
                FrmMessage.showDialog("Hata :" + ex.Message, MessageTypes.Error);
            }
        }
        #endregion

        #region Events...
        private void FrmModel_Load(object sender, EventArgs e)
        {
            LoadKalite();
            LoadTaban();
            LoadRenk();
            LoadDeri();
            LoadAstar();
            LoadLazer();
            LoadElSarac();
            LoadMakineSarac();
            LoadModeller();
        }

        private void btnKaydet_Click(object sender, EventArgs e)
        {
            if (kalite == null)
            {
                FrmMessage.showDialog("Lütfen kalite bilgilerini giriniz.", MessageTypes.Warning);
                return;
            }
            if (taban == null)
            {
                FrmMessage.showDialog("Lütfen taban bilgilerini giriniz.", MessageTypes.Warning);
                return;
            }
            if (deri == null)
            {
                FrmMessage.showDialog("Lütfen deri bilgilerini giriniz.", MessageTypes.Warning);
                return;
            }
            if (renk == null)
            {
                FrmMessage.showDialog("Lütfen renk bilgilerini giriniz.", MessageTypes.Warning);
                return;
            }
            if (resim == null)
            {
                FrmMessage.showDialog("Lütfen resim bilgilerini giriniz.", MessageTypes.Warning);
                return;
            }

            try
            {
                string imagePath = Application.StartupPath + "\\Image\\";

                if (!System.IO.File.Exists(imagePath))
                {
                    System.IO.Directory.CreateDirectory(imagePath);
                }

                string[] strImage = imageName.Split('.');
                string newImageName = strImage[0] + "_" + String.Format("{0:yyyyMMddHHmmss}", System.DateTime.Now) + "." + strImage[1];
                imagePath += newImageName;


                if (sqlCommandType.Equals(SqlCommandType.INSERT))
                {
                    string str = "kalite_id, taban_id, renk_id, deri_id, astar_id, lazer_id, elsarac_id, makinesarac_id, image_name, image_path";
                    string str2 = "@kalite_id, @taban_id, @renk_id, @deri_id, @astar_id, @lazer_id, @elsarac_id, @makinesarac_id, @image_name, @image_path";
                    string command = "INSERT INTO model ("+str+") VALUES ("+str2+")";
                    List<SqlParameter> list = new List<SqlParameter>();
                    list.Add(DBUtils.GetParameter("@kalite_id", kalite));
                    list.Add(DBUtils.GetParameter("@taban_id", taban));
                    list.Add(DBUtils.GetParameter("@renk_id", renk));
                    list.Add(DBUtils.GetParameter("@deri_id", deri));
                    list.Add(DBUtils.GetParameter("@astar_id", astar));
                    list.Add(DBUtils.GetParameter("@lazer_id", lazer));
                    list.Add(DBUtils.GetParameter("@elsarac_id", elSarac));
                    list.Add(DBUtils.GetParameter("@makinesarac_id", makineSarac));
                    list.Add(DBUtils.GetParameter("@image_name", imageName));
                    list.Add(DBUtils.GetParameter("@image_path", imagePath));

                    System.IO.File.Copy(fDialog.FileName, imagePath);
                    DBUtils.ExecuteSQLCommand(command, list);
                }
                else if (sqlCommandType.Equals(SqlCommandType.UPDATE))
                {

                    string str = "kalite_id=@kalite_id, taban_id=@taban_id, renk_id=@renk_id, deri_id=@deri_id, astar_id=@astar_id, lazer_id=@lazer_id, elsarac_id=@elsarac_id, makinesarac_id=@makinesarac_id";
                    
                    List<SqlParameter> list = new List<SqlParameter>();
                    list.Add(DBUtils.GetParameter("@kalite_id", kalite));
                    list.Add(DBUtils.GetParameter("@taban_id", taban));
                    list.Add(DBUtils.GetParameter("@renk_id", renk));
                    list.Add(DBUtils.GetParameter("@deri_id", deri));
                    list.Add(DBUtils.GetParameter("@astar_id", astar));
                    list.Add(DBUtils.GetParameter("@lazer_id", lazer));
                    list.Add(DBUtils.GetParameter("@elsarac_id", elSarac));
                    list.Add(DBUtils.GetParameter("@makinesarac_id", makineSarac));
                    list.Add(DBUtils.GetParameter("@model_id", modelId));

                    if (fDialog != null)
                    {
                        str += ", image_name=@image_name, image_path=@image_path";
                        list.Add(DBUtils.GetParameter("@image_name", imageName));
                        list.Add(DBUtils.GetParameter("@image_path", imagePath));
                        System.IO.File.Copy(fDialog.FileName, imagePath);
                    }

                    string command = "UPDATE model SET " + str + " WHERE model_id=@model_id";

                    DBUtils.ExecuteSQLCommand(command, list);
                }

                LoadModeller();
                clearForm();
            }
            catch (Exception ex)
            {
                FrmMessage.showDialog("Kayıt işlemi yapılırken hata oluştu. Hata :" + ex.Message, MessageTypes.Error);
            }
        }

        private void repbtnEdit_Click(object sender, EventArgs e)
        {
            modelId = SelectedRow["model_id"].ToString();
            kalite = Convert.ToInt32(SelectedRow["kalite_id"]);
            LoadTaban();
            taban = Convert.ToInt32(SelectedRow["taban_id"]);
            renk = Convert.ToInt32(SelectedRow["renk_id"]);
            deri = Convert.ToInt32(SelectedRow["deri_id"]);
            astar = (int?)(SelectedRow["astar_id"].Equals(DBNull.Value) ? null : SelectedRow["astar_id"]);
            lazer = (int?)(SelectedRow["lazer_id"].Equals(DBNull.Value) ? null : SelectedRow["lazer_id"]);
            elSarac = (int?)(SelectedRow["elsarac_id"].Equals(DBNull.Value) ? null : SelectedRow["elsarac_id"]);
            makineSarac = (int?)(SelectedRow["makinesarac_id"].Equals(DBNull.Value) ? null : SelectedRow["makinesarac_id"]);
            imageName = SelectedRow["image_name"].ToString();
            try
            {
                resim = new Bitmap(SelectedRow["image_path"].ToString());
            }catch(Exception ex){
                resim = FisApp.Properties.Resources.not_found;
            }
            sqlCommandType = SqlCommandType.UPDATE;
            btnVazgec.Visible = true;
        }

        private void repbtnDelete_Click(object sender, EventArgs e)
        {
            modelId = SelectedRow["model_id"].ToString();

            try
            {
                if (FrmMessage.ShowDialogResult(SelectedRow["model_id"].ToString() + " no'lu model bilgisini silmek istediğinize emin misiniz ?", MessageTypes.Question) == DialogResult.Yes)
                {
                    string command = "DELETE FROM model WHERE model_id=@model_id";

                    List<SqlParameter> list = new List<SqlParameter>();
                    list.Add(DBUtils.GetParameter("@model_id", modelId));
                    DBUtils.ExecuteSQLCommand(command, list);

                    LoadModeller();
                    clearForm();
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.ToString().Contains("-2146232060"))
                    FrmMessage.showDialog(General.ForeignKeyExceptionMessage, MessageTypes.Error);
                else
                    FrmMessage.showDialog("Silme işlemi yapılırken hata oluştu. Hata :" + ex.Message, MessageTypes.Error);

                //FrmMessage.showDialog("Silme işlemi yapılırken hata oluştu. Hata :" + ex.Message, MessageTypes.Error);
            }
        }

        private void btnVazgec_Click(object sender, EventArgs e)
        {
            clearForm();
        }

        private void tabanLookUp_QueryPopUp(object sender, CancelEventArgs e)
        {
            if (kalite == null)
            {
                FrmMessage.showDialog("Önce kalite seçiniz...", MessageTypes.Information);
                return;
            }
            LoadTaban();
        }

        private void FrmModel_Activated(object sender, EventArgs e)
        {
            FrmModel_Load(null,null); 
        }

        private void peResim_Click(object sender, EventArgs e)
        {
            fDialog = new OpenFileDialog();

            fDialog.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*";

            if (fDialog.ShowDialog() == DialogResult.OK)
            {
                peResim.EditValue = new Bitmap(fDialog.FileName);
                imageName = fDialog.SafeFileName;
            }
        }

        private void gvModel_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "Resim" && e.IsGetData)
            {
                try{
                    e.Value = new Bitmap((string)((DataRowView)e.Row)["image_path"]);// "";// imageCollection1.Images(0);  
                }catch(Exception ex){
                    e.Value = FisApp.Properties.Resources.not_found;
                }
            }
        }
        #endregion
    }
}
